<?php
namespace Api\Model;
use Think\Model,
    Admin\Model\GoodsModel,
    Admin\Model\SeekModel;

class TongbuModel extends Model
{
    public $m_a_goods;

    public function _initialize()
    {
        $this->m_a_goods = new GoodsModel();
    }

    /**
     * 由一个文件名，得到上级文件夹名
     *
     * @param string $file
     *
     * @return array
     */
    public function getDirName($file = '')
    {
        $file = trim($file); if($file == ''){ return null; }
        $file = str_replace(strrchr($file, '/'), '', $file);
        return $file;
    }

    /**
     * 同步一个商品
     *
     * @param array $post
     *
     * @return array
     */
    public function tongbuOneGoods($post = array())
    {
        /*
            需要入库的表：
                goods
                goods_attribute
                goods_option
                goods_pic
        */
        $err_msg = array();
        $the_time = time();

        //----------------------------Begin::goods表--------------------------
        $row_goods = array();

        if(isset($post['cid']) && intval($post['cid'])>0){
            $row_goods['cid'] = intval($post['cid']);
            //检查此分类是否存在
            $ck = $this->m_a_goods->getGoodsCategory(4, array('id'=>$row_goods['cid']));
            if(empty($ck)){
                $err_msg[] = '线上分类不存在';
            }
        }else{
            $err_msg[] = '缺少分类';
        }

        if(isset($post['code']) && $post['code']!=''){
            $row_goods['goods_code'] = $post['code'];
            //检查编码是否存在
            $ck = $this->m_a_goods->checkGoodsCode($row_goods['goods_code']);
            if($ck['st'] != 'no'){
                $err_msg[] = $ck['msg'];
            }
        }else{
            $err_msg[] = '缺少编码';
        }

        if(isset($post['price']) && floatval($post['price']) > 0){
            $row_goods['price'] = floatval($post['price']);
        }else{
            $err_msg[] = '缺少商品价格';
        }

        $row_goods['price_o'] = 0.0;
        $row_goods['price_s'] = 0.0;
        $row_goods['price_b'] = 0.0;

        if(isset($post['stock']) && intval($post['stock'])>0){
            $row_goods['stock'] = intval($post['stock']);
        }else{
            $row_goods['stock'] = 999;
        }

        if(isset($post['weight']) && floatval($post['weight']) > 0){
            $row_goods['weight'] = floatval($post['weight']);
        }else{
            $row_goods['weight'] = 0.3;
        }

        if(isset($post['pic']) && $post['pic']!=''){
            $row_goods['pic'] = $post['pic'];
        }else{
            $row_goods['pic'] = '';
        }

        if(isset($post['pic_back']) && $post['pic_back']!=''){
            $row_goods['pic_back'] = $post['pic_back'];
        }else{
            $row_goods['pic_back'] = '';
        }

        if(isset($post['goods_name']) && $post['goods_name']!=''){
            $row_goods['goods_name'] = $post['goods_name'];
        }else{
            $err_msg[] = '缺少商品名称';
        }

        if(isset($post['goods_intro']) && $post['goods_intro']!=''){
            $row_goods['goods_intro'] = $post['goods_intro'];
        }else{
            $err_msg[] = '缺少商品尺寸';
        }

        if(isset($post['goods_intro2']) && $post['goods_intro2']!=''){
            $row_goods['goods_intro2'] = $post['goods_intro2'];
        }

        $row_goods['brand_id'] = (isset($post['brand_id']) && intval($post['brand_id'])>0) ? intval($post['brand_id']) : 0;
        $row_goods['factory_id'] = (isset($post['factory_id']) && intval($post['factory_id'])>0) ? intval($post['factory_id']) : 0;
        $row_goods['ctime'] = $the_time;
        $row_goods['st'] = 0;
        $row_goods['add_time'] = date('Ymd', $the_time);
        $row_goods['star'] = 0;

        if(isset($post['collect_url']) && $post['collect_url']!=''){
            $row_goods['collect_url'] = $post['collect_url'];
        }else{
            $row_goods['collect_url'] = '';
        }

        $row_goods['view_ct'] = 0;
        $row_goods['link_id'] = 0;

        if( ! empty($err_msg)){ return array('st'=>'err', 'msg'=>$err_msg); }
        //----------------------------End::goods表--------------------------


        //----------------------------Begin::goods_attribute表------------------------
        $row_goods_attribute = array();

        $row_goods_attribute['cid'] = intval($post['cid']);

        if(isset($post['attribute_ids']) && $post['attribute_ids']!=''){
            $row_goods_attribute['attribute_ids'] = $post['attribute_ids'];
        }else{
            $row_goods_attribute['attribute_ids'] = '';
        }

        $row_goods_attribute['goods_st'] = 0;
        $row_goods_attribute['price'] = $row_goods['price'];
        //----------------------------End::goods_attribute表------------------------


        //----------------------------Begin::goods_option表------------------------
        //因为选项可能是多个，所以发送过来的必须是序列化后的数组
        $row_goods_option = array();
        if(isset($post['goods_options']) && $post['goods_options']!=''){
            $goods_options = unserialize($post['goods_options']);
            $i_op = 1;
            foreach($goods_options as $opt){
                $row_goods_option[$i_op] = array(
                    'option_id'=>$opt['site_option_id'],
                    'price_tag'=>$opt['price_tag'],
                    'price_range'=>$opt['price_range'],
                    'weight_tag'=>$opt['weight_tag'],
                    'weight_range'=>$opt['weight_range']
                );
                $i_op++;
            }
        }else{
            $err_msg[] = '缺少商品选项';
        }
        if( ! empty($err_msg)){ return array('st'=>'err', 'msg'=>$err_msg); }
        //----------------------------End::goods_option表------------------------


        //----------------------------Begin::goods_pic表------------------------
        //因为图片可能是多张，所以发送过来的必须是序列化后的数组
        $row_goods_pic = array();
        if(isset($post['goods_pics']) && $post['goods_pics']!=''){
            $goods_pics = unserialize($post['goods_pics']);
            $i_pic = 1;
            foreach($goods_pics as $pic){
                $pic_dir = $_SERVER['DOCUMENT_ROOT'].'/images'.$this->getDirName($pic['pic_path']);
                _mkDir($pic_dir);
                $row_goods_pic[$i_pic] = array(
                    'is_primary'=>$pic['is_primary'],
                    'is_back'=>$pic['is_back'],
                    'pic_num'=>$pic['pic_num'],
                    'pic_type'=>$pic['pic_type'],
                    'pic_path'=>$pic['pic_path'],
                    'pic_ext'=>$pic['pic_ext'],
                    'px'=>intval($pic['px']),
                );
                $i_pic++;
            }
        }else{
            $err_msg[] = '缺少商品图片';
        }
        if( ! empty($err_msg)){ return array('st'=>'err', 'msg'=>$err_msg); }
        //----------------------------End::goods_pic表------------------------

        /*ddd($row_goods,0,1);
        ddd($row_goods_attribute,0,1);
        ddd($row_goods_option,0,1);
        ddd($row_goods_pic,1,1);*/

        //入库goods
        $goods_id = $this->add($row_goods, array('table'=>getTable('tb_goods')));
        $goods_id = intval($goods_id); if($goods_id < 1){ $err_msg[] = '新增goods表记录错误'; return array('st'=>'err', 'msg'=>$err_msg); }
        //入库goods_attribute
        $row_goods_attribute['goods_id'] = $goods_id;
        $this->add($row_goods_attribute, array('table'=>getTable('tb_goods_attribute')));
        //入库goods_option
        foreach($row_goods_option as $x_op){
            $x_op['goods_id'] = $goods_id;
            $this->add($x_op, array('table'=>getTable('tb_goods_option')));
        }
        //入库goods_pic
        foreach($row_goods_pic as $x_pic){
            $x_pic['goods_id'] = $goods_id;
            $this->add($x_pic, array('table'=>getTable('tb_goods_pic')));
        }
        //最后处理一下"搜索关键词"
        $m_seek = new SeekModel();
        $m_seek->collectGoodsKeywords();

        return array('st'=>'ok', 'msg'=>$goods_id);
    }

    /**
     * 同步 goods_links
     *
     * @param array $post
     *
     * @return array
     */
    public function tongbuGoodsLinks($post = array())
    {
        if(!isset($post['links']) && $post['links']==''){ return array('st'=>'err', 'msg'=>'没有数据'); }
        $links = unserialize($post['links']);
        if(empty($links)){ return array('st'=>'err', 'msg'=>'没有数据'); }
        foreach($links as $lk){
            if($lk['link_codes'] != ''){
                //入库
                $insertID = $this->add(array('link_codes'=>$lk['link_codes']), array('table'=>getTable('tb_goods_links')));
                //商品逐个更新 ns_goods.link_id
                $codes = array();
                $tmp = explode(',', $lk['link_codes']);
                foreach($tmp as $t){
                    $t = trim($t);
                    if($t != ''){ $codes[] = $t; }
                }
                if( ! empty($codes)){
                    foreach($codes as $c){
                        $this->m_a_goods->updateGoodsByCode(array('link_id'=>$insertID), $c);
                    }
                }
            }
        }
        return array('st'=>'ok', 'msg'=>'ok');
    }

    /**
     * 得到一个订单信息
     *
     * @param int $order_sn
     *
     * @return array
     */
    public function getOrderBySn($order_sn = 0)
    {
        $tot_order = array();
        $where = " where order_sn =".$order_sn;
        $rs_order = $this->query("select * from " .getTable('tb_orders').$where);
        if( ! empty($rs_order))
        {
            $rs_order = array_shift($rs_order);
            $rs_order['orders_status'] = $rs_order['order_status'];
            //换算美元
            $currency_rate = $rs_order['currency_rate'];
            $rs_order['order_total'] = round($rs_order['order_total']/$currency_rate, 2);
            $rs_order['order_goods_total'] = round($rs_order['order_goods_total']/$currency_rate, 2);
            $rs_order['delivery_price'] = round($rs_order['delivery_price']/$currency_rate, 2);

            $res = $this->query("select login_account,reg_ip from ".getTable('tb_member_info')." where member_id=".$rs_order['member_id']);
            $rs_order['customers_email_address'] = $res[0]['login_account'];
            //$rs_order['ip_address'] = $res[0]['reg_ip'];
            $sql = "select * from " .getTable('tb_orders_status_history') . $where. " order by order_status_time limit 1";
            $rs_comments = $this->query($sql);
            $rs_order['comments'] = $rs_comments[0]['remark'];
            $sql = "select * from " .getTable('tb_orders_goods') . $where;
            $rs_order_products = $this->query($sql);
            if($rs_order_products){
                //ddd($rs_order_products,1,1);
                $tot_products_price = 0;
                foreach ($rs_order_products as $k=>$rop){
                    if($rop['the_type'] == 1 || $rop['the_type'] == 2 && $rop['cid'] == 1 || $rop['the_type'] == 3){
                        $tot_products_price+=$rop['price']*$rop['quantity'];
                        $rop['price'] = round($rop['price']/$currency_rate, 2);
                        $result = $rop;
                        $sql = "select a.*,b.option_name,b.pid from ".getTable('tb_orders_goods_option')."
	    				as a left join ".getTable('tb_option')." as b on a.option_id=b.id where a.order_sn=".$rop['order_sn']." and a.goods_id=".$rop['goods_id']." and a.orders_goods_id=".$rop['id'];
                        //echo $sql;exit;
                        $rs_order_products_attr = $this->query($sql);//ddd($rs_order_products_attr);
                        if($rs_order_products_attr){
                            $rs_order_products_attr = array_shift($rs_order_products_attr);
                            $res = $this->query("select option_name from ".getTable('tb_option')." where id=".$rs_order_products_attr['pid']);
                            $rs_order_products_attr['pid_option_name'] = $res[0]['option_name'];
                            $result['products_options'] = $rs_order_products_attr;
                        }
                        $rs_order['products'][] = $result;
                    }

                }
                foreach ($rs_order_products as $rr){
                    if($rr['the_type'] == 2 && $rr['cid'] == 2){
                        $rr['price'] = round(($tot_products_price*($rr['price']/100))/$currency_rate, 2);
                        $rs_order['products'][] = $rr;
                    }
                }
            }else{
                $rs = array('st'=>'ok', 'msg'=>'查无商品');
                return $rs;
            }
            //ddd($rs_order,1,1);
            $rs = array('st'=>'ok', 'msg'=>'ok', 'datas'=>$rs_order);
            return $rs;
        }
        else
        {
            $rs = array('st'=>'err', 'msg'=>'查无此订单');
            return $rs;
        }

    }
}